﻿using System;
using Microsoft.Xna.Framework;
using SomeGame.GUI.Widgets;

namespace SomeGame.GUI.WidgetActions {

    public class FadeAction : WidgetAction {

        public enum FadeType {

            In,
            Out

        }

        private readonly float AStep;
        private readonly float BStep;

        private readonly Vector4 ColorElements;
        private readonly float GStep;
        private readonly float RStep;
        private bool ADone;
        private float ASum;
        private bool BDone;
        private float BSum;
        private bool GDone;
        private float GSum;
        private bool RDone;
        private float RSum;

        public FadeAction(Widget widget,
            WidgetAction parent,
            WidgetActionState state,
            FadeType type,
            float seconds) : base(widget, parent, state) {
            // Capture original color.
            ColorElements = new Vector4(widget.CurrentColor.R,
                widget.CurrentColor.G,
                widget.CurrentColor.B,
                widget.CurrentColor.A);
            // Set Widget as transparent.
            Widget.CurrentColor = Color.Transparent;
            // Calculate steps.
            RStep = ColorElements.X/seconds/TimeSpan.TicksPerSecond;
            GStep = ColorElements.Y/seconds/TimeSpan.TicksPerSecond;
            BStep = ColorElements.Z/seconds/TimeSpan.TicksPerSecond;
            AStep = ColorElements.W/seconds/TimeSpan.TicksPerSecond;
        }

        public override void Update(GameTime gameTime) {
            RSum += RStep*gameTime.ElapsedGameTime.Ticks;
            if (RSum > ColorElements.X) {
                RSum = ColorElements.X;
                RDone = true;
            }
            GSum += GStep*gameTime.ElapsedGameTime.Ticks;
            if (GSum > ColorElements.Y) {
                GSum = ColorElements.Y;
                GDone = true;
            }
            BSum += BStep*gameTime.ElapsedGameTime.Ticks;
            if (BSum > ColorElements.Z) {
                BSum = ColorElements.Z;
                BDone = true;
            }
            ASum += AStep*gameTime.ElapsedGameTime.Ticks;
            if (ASum > ColorElements.W) {
                ASum = ColorElements.W;
                ADone = true;
            }
            Widget.CurrentColor = new Color(RSum/255f, GSum/255f, BSum/255f, ASum/255f);
            if (RDone && GDone && BDone && ADone) {
                State = WidgetActionState.Done;
            }
            base.Update(gameTime);
        }

    }

}